40923231 cp2020

  • Home
    • Site Map
    • reveal
    • blog
  • 首頁
  • homework1
    • PCH8 Cooling
      • Heat Sources(熱源)
      • BIOS Settings(BIOS設定)
      • Cooling Methods(冷卻方式)
      • Cooling Installation and Maintenance(冷卻安裝與維護)
      • Case Fans Installation(機箱風扇 安裝)
  • homework2
    • 2-1
    • 2-2
    • 2-3
  • homework3
    • 13 Fibonacci (費氏數列)
    • 21 Write To A File (文件編寫)
    • 35 Birthday Months(生日月份)
21 Write To A File (文件編寫) << Previous

35 Birthday Months(生日月份)

Exercise 35 (and Solution)

This exercise is Part 3 of 4 of the birthday data exercise series. The other exercises are: Part 1, Part 2, and Part 4.

此練習是生日數據練習系列4的第3部分。 其他練習是:第1部分,第2部分和第4部分。

In the previous exercise we saved information about famous scientists’ names and birthdays to disk. In this exercise, load that JSON file from disk, extract the months of all the birthdays, and count how many scientists have a birthday in each month.

在上一個練習中,我們將有關著名科學家的姓名和生日的信息保存到磁盤上。 在本練習中,從磁盤加載該JSON文件,提取所有生日的月份,併計算每個月有多少科學家生日。

Your program should output something like:

您的程序應輸出如下內容:

{
	"May": 3,
	"November": 2,
	"December": 1
}

Discussion(討論區)

You already have the skills to achieve this exercise with concepts we’ve already covered: for loops, dictionaries, and basic arithmetic. However, I want to talk about a Python built-in called a Counter

您已經具備使用我們已經介紹的概念完成此練習的技能:循環,字典和基本算術。 但是,我想談談一個稱為Counter的Python內置函數。

A Counter takes a list and counts how many of each element were in the list. To use the Counter, first import it from collections:

計數器獲取一個列表,併計算列表中每個元素的數量。 要使用計數器,請先從集合中將其導入:

from collections import Counter

This lets you use the Counter data structure built into Python in your program. Then, give it a list:

這使您可以在程序中使用Python內置的Counter數據結構。 然後,給它一個清單:

sandwiches = ["ham", "cheese", "roast beef", "ham", "cheese", "roast beef", "ham"]
c = Counter(sandwiches)
If you print(c), you will see this:

如果打印(c),將看到以下內容:

Counter({"ham": 3, "roast beef": 2, "cheese": 2})

This means there are 3 ham, 2 roast beef, and 2 cheese sandwiches in my list. I can get this information directly from the Counter:

這意味著我的列表中有3個火腿,2個烤牛肉和2個奶酪三明治。 我可以直接從櫃檯獲得此信息:

>>> print("There are {} ham sandwiches".format(c["ham"]))
There are 3 ham sandwiches
Hope this is useful!


21 Write To A File (文件編寫) << Previous

Copyright © All rights reserved | This template is made with by Colorlib